package mes.kanban.config;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import mes.kanban.aop.ShiroFlush;

/**
 * 注解使用拦截器
 * @author gjy
 *
 * 2018年2月12日下午5:50:04
 */
public class OperateAspect extends HandlerInterceptorAdapter {
	
	private static final Logger log = LoggerFactory.getLogger(OperateAspect.class);
	
	
	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse rep, Object handler) throws Exception {
		
		log.info("拦截器 执行.........................");
		
		MyShiroRealm myShiroRealm = null;
		
		BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(req.getServletContext()); 
		
		myShiroRealm = factory.getBean(MyShiroRealm.class);
		
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		// 从方法处理器中获取出要调用的方法
        Method method = handlerMethod.getMethod();
        
        //去除ShiroFlush注解
        ShiroFlush flush = method.getAnnotation(ShiroFlush.class);
        
        //如果没有注解，直接跳过
        if (flush == null) {
			return true;
		}
        
        log.info("有使用ShiroFlush注解.........................");
        
        try {
        	
        	 HttpSession session = WebUtils.toHttp(req).getSession();
             Object userinfoName = session.getAttribute("userSessionName");
             
        	 //清除掉当前用户的权限信息
             myShiroRealm.clearAuthz(req);
        	
            log.info("成功清除{"+userinfoName+"}权限");
            return true;
		} catch (Exception e) {
			e.printStackTrace();
			 log.info("权限清除失败，不能继续使用该功能："+method.getName());
		}
        
        log.info(method.getName()+"执行了清理权限的操作，请核查....................");
		
		return false;
	}

}
